package com.rslai.base.tool.servertest.paramfilter;

import com.alibaba.fastjson.JSONObject;
import com.rslai.base.tool.servertest.util.Util;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class NullParamFilter extends ParamFilter {
    protected String doHandle(String param) {
        if (Util.isJson(param)) {
            String json = setNullParam(param);
            return json;
        }
        if ((param.equals("NULL")) || (param.equals("[NULL]"))) {
            return null;
        }
        return param;
    }

    protected boolean support(String param) {
        return (param.equals("NULL")) || (param.equals("[NULL]")) || (param.contains("[NULL]"));
    }

    private String setNullParam(String param) {
        Map map = null;
        try {
            map = (Map) JSONObject.parse(param);
        } catch (Exception e) {
            return param;
        }
        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            if ("[NULL]".equals(entry.getValue())) {
                map.put(entry.getKey(), null);
            }
        }
        return JSONObject.toJSONString(map);
    }
}
